package com.wtwd.wtwddevice.service.impl;


import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.wtwd.device.util.DateUtils;
import com.wtwd.wtwddevice.mapper.DeviceSleepRecordMapper;
import com.wtwd.wtwddevice.model.entity.DeviceSleepRecord;
import com.wtwd.wtwddevice.service.IDeviceSleepRecordInfoService;
import com.wtwd.wtwddevice.service.IDeviceSleepRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mjy
 * @since 2024-05-31
 */
@Service
public class DeviceSleepRecordServiceImpl extends ServiceImpl<DeviceSleepRecordMapper, DeviceSleepRecord> implements IDeviceSleepRecordService {

    @Resource
    private DeviceSleepRecordMapper deviceSleepRecordMapper;

    @Resource
    private IDeviceSleepRecordInfoService deviceSleepRecordInfoService;


    @Override
    public boolean insertOrUpdate(DeviceSleepRecord deviceSleepRecord) {
        if (deviceSleepRecord == null) {
            return false;
        }
        return deviceSleepRecordMapper.insertOrUpdate(deviceSleepRecord);
    }

    @Override
    public DeviceSleepRecord getDeviceSleepByDeviceIdAndTime(Long deviceId, String time) {
        return new LambdaQueryChainWrapper<>(deviceSleepRecordMapper)
                .eq(DeviceSleepRecord::getDeviceId, deviceId)
                .eq(DeviceSleepRecord::getTime, time)
                .one();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public DeviceSleepRecord synchronousSleepRecord(DeviceSleepRecord deviceSleepRecord) {
        DeviceSleepRecord data = getDeviceSleepByDeviceIdAndTime(deviceSleepRecord.getDeviceId(), DateUtils.convertDateFormat(deviceSleepRecord.getTime()));
        if (data == null) {
            deviceSleepRecord.setTime(DateUtils.convertDateFormat(deviceSleepRecord.getTime()));
            save(deviceSleepRecord);
        } else {
            deviceSleepRecord.setId(data.getId());
            deviceSleepRecord.setTime(DateUtils.convertDateFormat(deviceSleepRecord.getTime()));
            updateById(deviceSleepRecord);
            //清除掉原本已经同步的睡眠详细信息数据
            deviceSleepRecordInfoService.deleteBySleepRecordId(data.getId());
        }
        return deviceSleepRecord;
    }
}
